<template>
    <div class="user-manage page">
        <div class="search-container">
            <el-form :inline="true" :model="searchForms" class="demo-form-inline">
                <el-form-item label="账号名称">
                    <el-input v-model="searchForms.login_name" :prefix-icon="UserFilled" placeholder="请输入账号名称" clearable />
                </el-form-item>
                <el-form-item label="手机号码">
                    <el-input v-model="searchForms.phonenumber" :prefix-icon="Cellphone" placeholder="请输入手机号码" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table-container">
            <div class="table-toolbar">
                <el-button type="primary" text bg :icon="Plus" @click="handleAdd">新增</el-button>
            </div>
            <div class="table-content">
                <el-table :data="tableData" border height="100%">
                    <el-table-column type="index" label="序号" width="70" />
                    <el-table-column prop="login_name" label="账号名称"/>
                    <el-table-column prop="user_name" label="用户名"/>
                    <el-table-column prop="phonenumber" label="手机号码" />
                    <el-table-column prop="email" label="邮箱" />
                    <el-table-column prop="status" label="状态">
                        <template #default="scope">
                            <el-tag
                                :type="scope.row.status === '0' ? 'success' : 'danger'"
                                >{{ scope.row.status === '0' ? '正常' : '停用' }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="create_time" label="创建时间" />
                    <el-table-column fixed="right" label="操作" width="180">
                        <template #default="scope">
                            <el-button link type="warning" :icon="Edit" @click="handleEdit(scope.row)">修改</el-button>
                            <el-button link type="danger" :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="table-pagination">
            <Paginations ref="pages" :total="total" @currentChange="currentChange"/>
        </div>
    </div>
    <!--新增修改弹出层--->
    <el-dialog v-model="dialog.show" :title="dialog.title" width="30%" draggable>
        <div class="dialog-content">
            <el-form
                ref="dialogFormRef"
                :model="dialogForm"
                :rules="dialogFormRules"
                label-width="auto"
                class="demo-ruleForm"
                size="default"
                status-icon
            >
                <el-form-item label="账号" prop="login_name">
                    <el-input v-model="dialogForm.login_name" placeholder="请输入账号" clearable />
                </el-form-item>
                <el-form-item label="账号密码" prop="password">
                    <el-input type="password" v-model="dialogForm.password" placeholder="请输入账号密码" show-password clearable />
                </el-form-item>
                <el-form-item label="用户名" prop="user_name">
                    <el-input v-model="dialogForm.user_name" placeholder="请输入用户名" clearable />
                </el-form-item>
                <el-form-item label="手机号码" prop="phonenumber">
                    <el-input v-model="dialogForm.phonenumber" placeholder="请输入手机号码" clearable />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input type="email" v-model="dialogForm.email" placeholder="请输入邮箱" clearable />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="dialogForm.status" placeholder="请选择状态">
                        <el-option label="正常" value="0" />
                        <el-option label="停用" value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="dialogForm.sex">
                        <el-radio value="0">男</el-radio>
                        <el-radio value="1">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="dialogForm.remark" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialog.show = false">取消</el-button>
                <el-button type="primary" @click="handleDialogSubmit(dialogFormRef)">
                确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
//引入elementPlus图标
import { Search, Edit, Delete, Plus, UserFilled, Cellphone } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
//引入api接口
import { getAllUser, addUser, updateUser } from '@/api/apis/user.ts';

interface User {
    login_name: string
    user_name: string
    phonenumber: string
    email: string
    status: string
    create_time: string
}
interface SearchForm {
    login_name: string
    phonenumber: string
}

interface DialogForm {
    user_id?: string,
    dept_id: number,
    login_name: string
    password: string
    user_name: string
    phonenumber: string
    email: string
    status: string
    remark: string
    sex: string
}

//搜索表单
const searchForms = reactive<SearchForm>({
    login_name: '',
    phonenumber: ''
})

//定义弹出层
let dialog = reactive({
    key: '',
    title: '',
    show: false
})
//新增修改表单
const dialogForm = reactive<DialogForm>({
    user_id: '',
    dept_id: 103,
    login_name: '',
    password: '',
    user_name: '',
    phonenumber: '',
    email: '',
    status: '',
    remark: '',
    sex: ''
})

//定义表格数据
let tableData = ref<User[]>([]);
let allTableData = ref<User[]>([]);
//定义分页数据
let total = ref<number>(0)
//定义分页ref
const pages = ref();
//定义表单ref
const dialogFormRef = ref()

//定义表单验证项
const dialogFormRules = reactive<FormRules<DialogForm>>({
    login_name: [
        { required: true, message: '请输入账号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入账号密码', trigger: 'blur' }
    ],
    user_name: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    phonenumber: [
        { required: true, message: '请输入手机号码', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ],
    sex: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    remark: [
        { required: true, message: '请输入备注', trigger: 'blur' }
    ]
})
//查询用户列表
const searchUsers = () => {
    allTableData.value = [];
    pages.value.pagination.currentPage = 1;
    getAllUser({}).then((res:any) => {
        if(res && res.code === 200) {
            allTableData.value = res.data;
            tableData.value = res.data.slice(0,10);
            total.value = res.data.length;
        }
    });
}

//监听子组件分页
const currentChange = (data: any) => {
    //计算显示数据
    tableData.value = allTableData.value.slice((data.currentPage - 1) * data.pageSize, data.currentPage * data.pageSize);
}
//搜索提交
const handleSearch = () => {
    searchUsers();
}

//新增数据
const handleAdd = () => {
    dialog.key = 'add';
    dialog.title = '新增';
    dialog.show = true;
    resetForm();
}

//修改数据
const handleEdit = (row:any) => {
    dialog.key = 'update';
    dialog.title = '修改';
    dialog.show = true;
    dialogForm.user_id = row.user_id;
    dialogForm.dept_id = row.dept_id;
    dialogForm.login_name = row.login_name;
    dialogForm.password = row.password;
    dialogForm.user_name = row.user_name;
    dialogForm.phonenumber = row.phonenumber;
    dialogForm.email = row.email;
    dialogForm.status = row.status;
    dialogForm.remark = row.remark;
    dialogForm.sex = row.sex;
}

//删除数据
const handleDelete = (row:any) => {
    console.log('delete data', row)
}

//新增修改提交
const handleDialogSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            if(dialog.key == 'add') {
                addUserSubmit()
            }else {
                updateUserSubmit()
            }
        } else {
            console.log('error submit!')
        }
    })
}

//重置表单
const resetForm = () => {
    dialogFormRef.value.resetFields()
}

//新增接口调用
const addUserSubmit = () => {
    addUser(dialogForm).then((res:any) => {
        if(res && res.code === 200) {
            dialog.show = false;
            searchUsers();
            ElMessage({
                message: '新增成功！',
                type: 'success',
            })
        }else {
            ElMessage({
                message: '新增失败！',
                type: 'error',
            })
        }
    })
}

//修改接口调用
const updateUserSubmit = () => {
    updateUser(dialogForm).then((res:any) => {
        if(res && res.code === 200) {
            dialog.show = false;
            searchUsers();
            ElMessage({
                message: '修改成功！',
                type: 'success',
            })
        }else {
            ElMessage({
                message: '修改失败！',
                type: 'error',
            })
        }
    })
}

onMounted(() => {
    searchUsers();
});

</script>
<style lang="scss" scoped>
.user-manage {
   width: 100%;
}
</style>